package com.bookmanager.www.controller;


import com.bookmanager.www.common.DTO.BatchChangeCheckedTypeDTO;
import com.bookmanager.www.common.utils.Result;
import com.bookmanager.www.entity.FlBook;
import com.bookmanager.www.entity.FlCarts;
import com.bookmanager.www.entity.FlUser;
import com.bookmanager.www.mapper.FlBookMapper;
import com.bookmanager.www.mapper.FlCartsMapper;
import com.bookmanager.www.mapper.FlUserMapper;
import com.bookmanager.www.service.FlCartsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户购物车 前端控制器
 * </p>
 *
 * @author 风离
 * @since 2021-09-17
 */
@RestController
@RequestMapping("/fl-carts")
@Api(tags="购物车管理")
public class FlCartsController {

    @Resource
    FlUserMapper flUserMapper;
    @Resource
    FlCartsService flCartsService;

    @Resource
    FlBookMapper flBookMapper;
    @Resource
    FlCartsMapper flCartsMapper;

    /**
     * 删除商品分为 单个删除 全选删除 多选删除(感觉多选删除包括全选删除 前端完成全选过程)
     * @param username
     * @param bookId
     * @return
     */

    @DeleteMapping("/deleteOne")
    @ApiOperation(value="删除一个商品",notes="从购物车列表中删除一个商品 传入BookId username 即可")
    Result deleteOne(@RequestParam("username")String username,@RequestParam("bookId")String bookId)
    {
        FlUser flUser =flUserMapper.selectUserByUsername(username);
        String userId=flUser.getUserId();

        int deleteOne = flCartsMapper.deleteOne(userId,bookId);
        if(deleteOne!=0)
        {
            return Result.succ("删除商品成功！","");
        }

        return Result.fail("删除商品失败","");
    }

    @DeleteMapping("/deleteBatch")
    @ApiOperation(value="删除多个商品",notes=" 传入多个商品id 和username即可")
    Result deleteBatch(@RequestParam("username")String username,@RequestParam("bookIds")String[] bookIds)
    {
        FlUser flUser =flUserMapper.selectUserByUsername(username);
        String userId=flUser.getUserId();
        int deleteBatch = flCartsMapper.deleteBatch(userId,bookIds);
        System.out.println("删除的商品数为："+deleteBatch);
        if(deleteBatch!=bookIds.length)
        {
            return Result.fail("删除多个商品失败","");
        }

        return Result.succ("删除"+deleteBatch+"个商品成功！","");

    }


    @PostMapping("/batchChangeCheckedType")
    // @RequestBody BatchChangeCheckedTypeDTO bDTO
    @ApiOperation(value = "多选改变勾选状态",notes = "传入用户名 图书id 勾选状态 1 已勾选 0 未勾选")
    Result batchChangeCheckedType(
            @RequestParam("userId")String userId,@RequestParam("bookIds")String[] bookIds,@RequestParam("checkedType")Integer checkedType
    ){

        //更新数量为
        int count=0;
        for(int i=0;i<bookIds.length;i++)
        {
            int updated = flCartsMapper.changeCheckedType(userId,bookIds[i],checkedType);
            if(updated!=0)
            {
                count++;
            }
        }
        return Result.succ("改变状态成功！！！更新数量为："+count,count);
    }
//    @PostMapping("/batchChangeCheckedType")
//    @ApiOperation(value = "多选改变勾选状态",notes = "传入用户名 图书id 勾选状态 1 已勾选 0 未勾选")
//    Result batchChangeCheckedType(
//            @RequestBody BatchChangeCheckedTypeDTO bDTO
//            ){
//
//        //更新数量为
//        int count=0;
//       for(int i=0;i<bDTO.getBookIds().length;i++)
//       {
//           int updated = flCartsMapper.changeCheckedType(bDTO.getUserId(),bDTO.getBookIds()[i],bDTO.getCheckedType());
//           if(updated!=0)
//           {
//               count++;
//           }
//       }
//        return Result.succ("改变状态成功！！！更新数量为：",count);
//    }

    /**
     * 勾选或者取消勾选购物车
     * @return
     */
    @PostMapping("/changeCheckedType")
    @ApiOperation(value="改变勾选状态",notes="传入用户名 图书id 勾选状态 1 已勾选 0 未勾选")
    Result changeCheckedType(@RequestParam("username")String username,@RequestParam("bookId")String bookId,
                             @RequestParam("checkedType")Integer checkedType)
    {
        String userId =flUserMapper.selectUserByUsername(username).getUserId();

      int updated = flCartsMapper.changeCheckedType(userId,bookId,checkedType);
      if(updated!=0)
      {
          return Result.succ("改变状态成功！！","");
      }
        return Result.fail("改变状态失败！！！","");
    }

    /**
     * 全选购物车 或者取消全选
     * @return
     */
    @PostMapping("/changeAllCheckedType")
    @ApiOperation(value="改变所有的商品勾选状态",notes="传入用户名 图书id 勾选状态 1 已勾选 0 未勾选")
    Result changeAllCheckedType(@RequestParam("username")String username,
                             @RequestParam("checkedType")Integer checkedType)
    {
        String userId =flUserMapper.selectUserByUsername(username).getUserId();
        int updated = flCartsMapper.changeAllCheckedType(userId,checkedType);
        if(updated!=0)
        {
            return Result.succ("改变状态成功！！","");
        }
        return Result.fail("改变状态失败！！！","");

    }



    @GetMapping("/selectAllCarts")
    @ApiOperation(value="查询所有用户购物车信息",notes="需要管理员权限")
    @RequiresRoles(value = {"admin"})
    Result selectAllCarts()
    {
        List<FlCarts> flCartsList = flCartsMapper.selectAllCarts();
        if (flCartsList!=null)
        {
            return Result.succ("查询所有购物车成功！！",flCartsList);
        }

        return Result.fail("查询失败","");
    }


    @PostMapping("/getUserTotalCartsPrice")
    @ApiOperation(value="获取用户购物车总价值",notes="包含所有选中状态 checked=1 如果未选中则不计入")
    Result getUserTotalCartsPrice(@RequestParam("username")String username)
    {
        String userId =flUserMapper.selectUserByUsername(username).getUserId();
        double strPrice = flCartsService.getAllCartsPrice(userId);

        return Result.succ("获取用户购物车总价值成功！",strPrice+" 元");
    }

    @GetMapping("/selectAllCartsByUsername")
    @ApiOperation(value="查询用户购物车",notes = "")
    /**
     *  通过用户名查询购物车信息
     */
    Result selectAllCartsByUsername(@RequestParam("username")String username)
    {
        String userId =flUserMapper.selectUserByUsername(username).getUserId();
        List<FlCarts> flCartsList =flCartsMapper.selectCartsByUserId(userId);


        return Result.succ("查询购物车信息成功",flCartsList);
    }

    @PostMapping("/addBookToCarts")
    @ApiOperation(value = "添加图书到购物车",notes="")
    /**
     * 添加到购物车逻辑：
     * 首先判断是否存在购物车
     * 如果不存在购物车就新建购物车
     * 如果存在 就添加图书到购物车 默认已勾选提交购物车选项
     * 如果图书id已存在就count++
     *
     * 关于传参 ： 传入用户名 图书id 关于图书数量 前端传一个count
     */
    Result addBookToCarts(@RequestParam("username") String username,
                          @RequestParam("bookId")String bookId,
                          @RequestParam("count")int count)
    {
        FlUser flUser = flUserMapper.selectUserByUsername(username);
        String userId = flUser.getUserId();
        List<FlCarts> flCartsList = flCartsService.selectCartsByUserId(userId);
        System.out.println("该用户拥有的购物车为："+flCartsList);
        System.out.println("该用户是否拥有购物车====>"+flCartsList.size());
        if(flCartsList.size()==0)
        {
           int insert = flCartsService.createCartForUser(userId,bookId,count);
           if(insert!=0)
           {
               return Result.succ("添加图书到购物车成功！","");
           }
        }else{
            //如果该图书存在
            FlCarts existBook = flCartsMapper.selectCartsByBookIdAndUserId(bookId,userId);
            if(existBook!=null)
            {
//                int total = existBook.getCount()+count;
                int updateCountByBookId = flCartsMapper.updateCountByBookId(bookId,count);
                if (updateCountByBookId!=0)
                {
                    return Result.succ("图书数量增加了！","该图书数量目前为："+count);
                }
            }
            int insert = flCartsService.addBookToCarts(userId,bookId,count);
            if(insert!=0)
            {
                return Result.succ("添加图书到购物车成功！","");
            }
        }
        return Result.fail("添加图书到购物车失败！","");

    }

    @PostMapping("/ifAddBookToCarts")
    @ApiOperation(value = "判断用户是否添加图书到购物车",notes = "传userId bookId")
    Result ifAddBookToCarts(@RequestParam("userId")String userId,@RequestParam("bookId")String bookId)
    {
        //如果该图书存在
        FlCarts existBook = flCartsMapper.selectCartsByBookIdAndUserId(bookId,userId);
        if(existBook!=null)
        {
            return Result.fail("该用户已添加该商品到购物车","");
        }
        return Result.succ("该用户尚未添加商品到购物车","");
    }



}
